package myJs

import myJs.Implicits._
import myJs.Utils.layer
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._
import shared.VarTool

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 6/5/2021
 */
@JSExportTopLevel("SearchResult")
object SearchResult {

  val tableId = "table"
  val formId = "form"
  val imageId="image"

  @JSExport("init")
  def init = {
    initText
    initTable
    refreshTable
    refreshHeatmap
    registerEvent
  }

  def initText = {
    val data = Tool.getTextData(getKind)
    $("#showName").text(data.showName)
    $("#tag").text(data.tag)
  }

  def initTable = {
    val tableJq = $("#table")
    getKind match {
      case VarTool.mRnaKind => MrnaBrowse.initTable(tableJq,isServerSide = false)
      case VarTool.circRnaKind => CircRnaBrowse.initTable(tableJq,isServerSide = false)
      case VarTool.pathwayKind => PathwayBrowse.initTable(tableJq,isServerSide = false)
      case VarTool.cellKind => CellBrowse.initTable(tableJq)
    }
  }

  def getIdStr = {
    g.id.toString
  }

  def getKind = {
    g.kind.toString
  }

  def refreshLinear = {
    Tool.useLoadingF() { () =>
      refreshLinearF
    }
  }

  def refreshHeatmap = {
    Tool.useLoadingF() { () =>
      refreshHeatmapF
    }
  }

  def refreshLinearF = {
    val idStr = getIdStr
    val url = g.jsRoutes.controllers.SearchController.getLinearImage().url.toString
    val dict = js.Dictionary(
      "geneSymbol" -> idStr,
      "kind" -> getKind
    )
    val data = JSON.stringify(dict)
    Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val valid = rs("valid").toB
      if (valid) {
        val base64 = rs("base64")
        val imageJq=$(s"#${imageId}")
        imageJq.attr("src", s"data:image/png;base64,${base64}")
        imageJq.attr(Tool.dataBasicType, s"pdf")
        imageJq.parents(".myCharts").findInputByName("pdfBase64").
          `val`(rs("pdfBase64").toString)
      } else {
        Swal.swal(SwalOptions.title("Error").text(rs("message")).`type`("error"))
      }
    }

  }

  def refreshHeatmapF = {
    val idStr = getIdStr
    val url = g.jsRoutes.controllers.SearchController.getHeatmapImage().url.toString
    val dict = js.Dictionary(
      "geneSymbol" -> idStr,
      "kind" -> getKind
    )
    val data = JSON.stringify(dict)
    Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val valid = rs("valid").toB
      if (valid) {
        val base64 = rs("base64")
        val imageJq=$(s"#${imageId}")
        imageJq.attr("src", s"data:image/png;base64,${base64}")
        imageJq.attr(Tool.dataBasicType, s"pdf")
        imageJq.parents(".myCharts").findInputByName("pdfBase64").
          `val`(rs("pdfBase64").toString)
      } else {
        Swal.swal(SwalOptions.title("Error").text(rs("message")).`type`("error"))
      }
    }

  }

  def registerEvent = {
    $(document.body).on("click", s".myLinear", "", (y: Element) => {
      refreshLinear
    })
    $(document.body).on("click", s".myHeatmap", "", (y: Element) => {
      refreshHeatmap
    })
  }

  def refreshTable = {
    val url = (getKind match {
      case VarTool.mRnaKind => g.jsRoutes.controllers.MrnaController.getAllByGeneNames().url.toString
      case VarTool.circRnaKind => g.jsRoutes.controllers.CircRnaController.searchAllByGeneSymbolOrId().url.toString
      case VarTool.pathwayKind => g.jsRoutes.controllers.PathwayController.searchAllByIdOrName().url.toString
      case VarTool.cellKind => g.jsRoutes.controllers.CellController.selectAllByName().url.toString
    })
    val dict = js.Dictionary(
      "id" -> getIdStr,
    )
    val data = JSON.stringify(dict)
    Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val data = xhr.responseText.toJArJDS
      $(s"#${tableId}").bootstrapTable("load", data)
    }
  }


}
